package com.jetpack.mvvm.lib.base

import android.app.Activity
import android.app.Application
import android.util.Log
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import com.jetpack.mvvm.lib.base.interf.ShareViewModelInterface

class ShareViewModelImpl(private val application: Application) : ViewModelStoreOwner, ShareViewModelInterface {
    companion object {
        private const val TAG = "ShareViewModelImpl"
    }

    private lateinit var appViewModelStore: ViewModelStore
    private lateinit var viewModelProvider: ViewModelProvider
    private lateinit var factory: ViewModelProvider.Factory

    override fun getViewModelStore(): ViewModelStore {
        if (!::appViewModelStore.isInitialized) {
            appViewModelStore = ViewModelStore()
            factory = ViewModelProvider.AndroidViewModelFactory(application)
            viewModelProvider = ViewModelProvider(appViewModelStore, factory)
        }
        return appViewModelStore
    }

    override fun getViewModelFactory(): ViewModelProvider.Factory {
        ensureViewModelStore()
        return factory
    }

    override fun getAppViewModelProvider(): ViewModelProvider {
        ensureViewModelStore()
        return viewModelProvider
    }

    /**
     * 通过 activity 中获取全局共享 ViewModelProvider
     */
    override fun getAppViewModelProvider(activity: Activity): ViewModelProvider {
        ensureViewModelStore()
        checkApplication(activity)
        return viewModelProvider
    }

    /**
     * 通过 fragment 中获取全局共享 ViewModelProvider
     */
    override fun getAppViewModelProvider(fragment: Fragment): ViewModelProvider {
        ensureViewModelStore()
        return getAppViewModelProvider(fragment.requireActivity())
    }

    private fun ensureViewModelStore() {
        this::getViewModelStore.invoke()
    }

    private fun checkApplication(activity: Activity): Application {
        return activity.application
            ?: throw IllegalStateException(
                "Your activity is not yet attached to the Application instance." +
                        "You can't request ViewModel before onCreate call."
            )
    }
}